<template>
  <div class="price-edit-container">
    <a-spin
      :loading="pageLoading"
      :size="35"
      class="w-[100%]"
      tip="正在加载, 请稍候..."
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        auto-label-width
        class="mt-4"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="priceName" label="价格名称" required>
              <a-input
                v-model="editForm.priceName"
                placeholder="请输入价格名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="priceType" label="价格类型" required>
              <a-select
                v-model="editForm.priceType"
                allow-clear
                placeholder="请选择价格类型"
              >
                <a-option
                  v-for="(d, index) in dicts[proxy.DICT.lindiPriceType]"
                  :key="index"
                  :label="d.dictValue"
                  :value="String(d.dictKey)"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="unitPrice" label="单价(万元/亩)" required>
              <a-input
                v-model="editForm.unitPrice"
                placeholder="请输入单价"
                class="w-[100%]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="effectiveDate" label="生效时间" required>
              <a-date-picker
                v-model="editForm.effectiveDate"
                class="w-[100%]"
                disabled-input
                format="YYYY-MM-DD HH:mm:ss"
                show-time
                placeholder="请选择生效时间"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="expireTime" label="失效时间">
              <a-date-picker
                v-model="editForm.expireTime"
                class="w-[100%]"
                disabled-input
                format="YYYY-MM-DD HH:mm:ss"
                show-time
                placeholder="请选择失效时间(可为空)"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="remark" label="备注说明">
              <a-input v-model="editForm.remark" placeholder="请输入备注说明" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>

    <!-- 操作按钮 -->
    <div class="flex justify-end mt-4">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="saveEdit" :loading="saveLoading">
          保存
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  addPriceConfigApi,
  updatePriceConfigByPriceConfigIdApi,
  getPriceConfigByPriceConfigIdApi,
} from "~/api/lindi/priceConfig";

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit事件
const emit = defineEmits(["cancel", "ok"]);

//全局实例
const { proxy } = getCurrentInstance();
//路由实例
const router = useRouter();
const route = useRoute();

//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.lindiPriceType]);

// 页面状态
const pageLoading = ref(false);
const saveLoading = ref(false);
const isEdit = ref(false);
const priceConfigId = ref(null);

// 编辑表单数据
const editForm = reactive({
  priceConfigId: null,
  priceName: null,
  priceType: null,
  unitPrice: null,
  effectiveDate: null,
  expireTime: null,
  remark: null,
});

// 编辑表单引用
const editFormRef = ref(null);

// 编辑表单校验规则
const editRules = {
  priceName: [
    { required: true, message: "价格名称不能为空", trigger: "submit" },
  ],
  priceType: [
    { required: true, message: "价格类型不能为空", trigger: "submit" },
  ],
  unitPrice: [{ required: true, message: "单价不能为空", trigger: "submit" }],
  effectiveDate: [
    { required: true, message: "生效时间不能为空", trigger: "submit" },
  ],
};

// 取消操作
const handleCancel = () => {
  // 如果是在模态框中，发送取消事件
  if (props.params && Object.keys(props.params).length > 0) {
    emit("cancel");
  } else {
    // 如果是独立页面访问，返回上一页
    router.back();
  }
};

// 返回上一页（保持兼容性）
const goBack = () => {
  handleCancel();
};

// 加载详情数据
const loadDetail = () => {
  if (!priceConfigId.value) return;

  pageLoading.value = true;

  getPriceConfigByPriceConfigIdApi(priceConfigId.value)
    .then((response) => {
      console.log(response);
      Object.keys(editForm).forEach((key) => {
        if (response.hasOwnProperty(key)) {
          editForm[key] = response[key];
        }
      });
    })
    .catch((error) => {
      console.error("获取价格配置详情失败:", error);
      proxy.$msg.error("加载数据失败");
    })
    .finally(() => {
      pageLoading.value = false;
    });
};

// 保存编辑
const saveEdit = () => {
  editFormRef.value.validate((errors) => {
    if (!errors) {
      saveLoading.value = true;

      const apiCall = isEdit.value
        ? updatePriceConfigByPriceConfigIdApi(editForm)
        : addPriceConfigApi(editForm);

      apiCall
        .then((response) => {
          proxy.$msg.success(
            isEdit.value ? "修改价格配置成功" : "添加价格配置成功"
          );

          // 如果是在模态框中，发送确定事件
          if (props.params && Object.keys(props.params).length > 0) {
            emit("ok");
          } else {
            // 如果是独立页面访问，返回列表页
            router.push("/lindi/price/mgt");
          }
        })
        .catch((error) => {
          console.error("保存价格配置失败:", error);
          proxy.$msg.error(
            isEdit.value ? "修改价格配置失败" : "添加价格配置失败"
          );
        })
        .finally(() => {
          saveLoading.value = false;
        });
    }
  });
};

// 监听props变化
watch(
  () => props.params,
  (newParams) => {
    if (newParams && newParams.priceConfigId) {
      priceConfigId.value = newParams.priceConfigId;
      isEdit.value = true;
      loadDetail();
    } else if (
      newParams &&
      newParams.operationType === proxy.operationType.add.type
    ) {
      // 新增模式
      priceConfigId.value = null;
      isEdit.value = false;
      // 重置表单
      Object.keys(editForm).forEach((key) => {
        editForm[key] = null;
      });
    }
  },
  { immediate: true }
);

// 页面初始化
onMounted(() => {
  // 如果没有通过props传递参数，则从路由获取
  if (!props.params || Object.keys(props.params).length === 0) {
    priceConfigId.value = route.query.id;
    isEdit.value = !!priceConfigId.value;

    // 如果是编辑模式，加载详情数据
    if (isEdit.value) {
      loadDetail();
    }
  }
});
</script>

<style scoped>
.price-edit-container {
  padding: 16px;
  max-height: 70vh;
  overflow-y: auto;
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 16px;
}
</style>
